package weather

import (
	"encoding/json"
	"gin-base/base/config"
	"github.com/parnurzeal/gorequest"
)

const serverAddress = "https://api.seniverse.com"

var serverAppSecret string

func init() {

	serverAppSecret = config.Ini.String("xinzhi.secret")
}

func GetNowWeatherData(location string) map[string]interface{} {
	url := serverAddress + "/v3/weather/now.json?" + "key=" + serverAppSecret + "&location=" + location

	_, body, errs := gorequest.New().Get(url).End()
	if errs != nil {
		return nil
	}
	var data interface{}

	json.Unmarshal([]byte(body), &data)
	r := data.(map[string]interface{})

	val, exist := r["results"]
	if !exist {
		return nil
	}

	a := val.([]interface{})
	now := a[0].(map[string]interface{})

	return now["now"].(map[string]interface{})
}

func GetNowAirData(location string) map[string]interface{} {
	url := serverAddress + "/v3/air/now.json?" + "key=" + serverAppSecret + "&location=" + location
	_, body, errs := gorequest.New().Get(url).End()
	if errs != nil {
		return nil
	}
	var data interface{}

	json.Unmarshal([]byte(body), &data)
	r := data.(map[string]interface{})

	_, exist := r["results"]
	if !exist {
		return r
	}

	arr := r["results"].([]interface{})
	now := arr[0].(map[string]interface{})

	city := now["air"].(map[string]interface{})
	return city["city"].(map[string]interface{})
}

func GetNowLifeData(location string) map[string]interface{} {
	url := serverAddress + "/v3/life/suggestion.json?" + "key=" + serverAppSecret + "&location=" + location
	_, body, errs := gorequest.New().Get(url).End()
	if errs != nil {
		return nil
	}
	var data interface{}

	json.Unmarshal([]byte(body), &data)
	r := data.(map[string]interface{})

	_, exist := r["results"]
	if !exist {
		return r
	}

	arr := r["results"].([]interface{})
	now := arr[0].(map[string]interface{})

	suggestion := now["suggestion"].(map[string]interface{})
	return suggestion
}

func GetNowData(location string) map[string]interface{} {
	nowAirData := GetNowAirData(location)
	nowWeatherData := GetNowWeatherData(location)
	nowLifeData := GetNowLifeData(location)

	info := make(map[string]interface{})
	info["air"] = nowAirData
	info["weather"] = nowWeatherData
	info["life"] = nowLifeData

	return info
}
